package com.c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.c.entity.*;
import com.c.mapper.*;
import com.c.service.OrderService;
import com.c.service.UserService;
import com.c.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author wangxiangli
 * @create 2022-12-25-12:30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {



    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private MemberFileReportMapper memberFileReportMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private TodayInformationMapper todayInformationMapper;
    @Autowired
    private TotalInformationMapper totalInformationMapper;


    @Autowired
    private  OrderFormMapper orderFormMapper;
    /**
     * 分页查找订单
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        IPage<Map> page2=new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //忽略空格查询条件
        if (queryPageBean.getQueryString() != null && queryPageBean.getQueryString().length() > 0) {
            queryString = queryPageBean.getQueryString().trim();// 去除查询条件首尾空格
        }
        IPage<Map> page = baseMapper.findByPage(page2,queryString);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 添加预约订单
     *
     * @param map
     * @return
     */
    @Override
    public Result order(Map map) throws Exception {
        // 0、判断预约的地址是否是正确的  返回的公司地址对应的id
        int addressId;
        try {
            addressId = addressMapper.findCountByAddressName((String) map.get("companyAddress"));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(false, MessageConstant.SELECTED_ADDRESS_FAIL);
        }

        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("orderDate",orderDate);
        OrderSetting orderSetting = orderSettingMapper.selectOne(wrapper);
        if (orderSetting == null) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("phoneNumber",telephone);
        Member member = memberMapper.selectOne(wrapper1);
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = baseMapper.findByCondition(order);
            if (list != null && list.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
            //SnowFlakeGenerateIdWorkerutil snowFlakeGenerateIdWorkerutil = new SnowFlakeGenerateIdWorkerutil(0L,0L);
            //String fileNumberid= snowFlakeGenerateIdWorkerutil.generateNextId().substring(0,12);
            //member.setFileNumber(fileNumberid);//档案号
            member.setName((String) map.get("name"));
            member.setPassword(MD5Utils.md5("123456"));//设置默认密码123456
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setRegTime(new Date());
            memberMapper.updateById(member);
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            SnowFlakeGenerateIdWorkerutil snowFlakeGenerateIdWorkerutil = new SnowFlakeGenerateIdWorkerutil(0L,0L);
            String fileNumberid= snowFlakeGenerateIdWorkerutil.generateNextId().substring(0,12);
            member.setFileNumber(fileNumberid);//档案号
            member.setName((String) map.get("name"));
            member.setPassword(MD5Utils.md5("123456"));//设置默认密码123456
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setEmail((String)map.get("email"));
            member.setSex((String) map.get("sex"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setRegTime(new Date());
            memberMapper.insert(member);//自动完成会员注册
        }

        //添加订单号
        Setmeal setmeal = setmealMapper.selectById(Integer.parseInt((String) map.get("setmealId")));
        //获取所有健康管理师
        List<User> healthDoctors = userService.getUserByRemark();
        Random rand=new Random(47);
        //随机排序分配健康管理师
        Collections.shuffle(healthDoctors,rand);
        OrderForm orderForm=new OrderForm();
        orderForm.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        orderForm.setSetmealId(setmeal.getId());
        orderForm.setSetmealName(setmeal.getName());
        orderForm.setSetmealCover(setmeal.getImg());
        orderForm.setDoctorId(healthDoctors.get(0).getId());
        orderForm.setDoctorRealname(healthDoctors.get(0).getRealname());
        orderForm.setMemberId(member.getId());
        orderForm.setMemberName(member.getName());
        orderForm.setMobile(member.getPhoneNumber());
        orderForm.setTotalFee(setmeal.getPrice());
        orderForm.setPayType(0);//其他支付类型
        orderForm.setStatus(1);//已支付
        orderForm.setOrderDate(DateUtils.parseString2Date(orderDate));
        orderFormMapper.insert(orderForm);



        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        order.setAddressId(addressId);
        baseMapper.insert(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingMapper.updateById(orderSetting);

        //更新今日预约人数和总预约人数
        QueryWrapper<TodayInformation> todayInformationQueryWrapper=new QueryWrapper<>();
        String date2String = DateUtils.parseDate2String(new Date());
        todayInformationQueryWrapper.eq("todaydate",date2String);
        TodayInformation todayInformation = todayInformationMapper.selectOne(todayInformationQueryWrapper);
        List<TotalInformation> totalInformations = totalInformationMapper.selectList(null);
        if(Objects.isNull(todayInformation)){
            TodayInformation todayInformation1=new TodayInformation();
            todayInformation1.setTodayordernumber(1);
            todayInformation1.setTodayestimatenumber(0);
            todayInformation1.setTodayintervenenumber(0);
            todayInformation1.setTodaycommentnumber(0);
            Date newdate = DateUtils.parseString2Date(DateUtils.parseDate2String(new Date()));
            todayInformation1.setTodayDate(newdate);
            todayInformationMapper.insert(todayInformation1);
            TotalInformation totalInformation = totalInformations.get(0);
            totalInformation.setTotalordernumber(totalInformation.getTotalordernumber()+1);
            totalInformationMapper.updateById(totalInformation);
        }else{
            todayInformation.setTodayordernumber(todayInformation.getTodayordernumber()+1);
            todayInformationMapper.updateById(todayInformation);
            TotalInformation totalInformation = totalInformations.get(0);
            totalInformation.setTotalordernumber(totalInformation.getTotalordernumber()+1);
            totalInformationMapper.updateById(totalInformation);
        }

        this.addMemberFileReport(member, order);//添加体检报告
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 添加体检报告
     *
     * @param member
     * @param order
     */
    public void addMemberFileReport(Member member, Order order) {
        SnowFlakeGenerateIdWorkerutil snowFlakeGenerateIdWorkerutil = new SnowFlakeGenerateIdWorkerutil(0L,0L);
        String checkNumberid= snowFlakeGenerateIdWorkerutil.generateNextId().substring(0,12);
        MemberFileReport memberFileReport = new MemberFileReport();
        memberFileReport.setFileNumber(member.getFileNumber());//档案号
        memberFileReport.setCheckNumber(checkNumberid);
        memberFileReport.setName(member.getName());//姓名
        memberFileReport.setSex(member.getSex());//性别
        memberFileReport.setPhoneNumber(member.getPhoneNumber());//手机号
        memberFileReport.setCheckuptime(order.getOrderDate());//体检日期
        memberFileReport.setMemberId(member.getId());
        Setmeal setmeal = setmealMapper.selectById(order.getSetmealId());

        memberFileReport.setSetmealId(order.getSetmealId());//套餐ID
        memberFileReport.setSetmealName(setmeal.getName());//套餐名称

//        memberFileReport.setFileurl(null);//档案地址
        memberFileReport.setFilestatus("0");//报告状态
        memberFileReportMapper.insert(memberFileReport);
    }
    /**
     * 根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = baseMapper.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    /**
     * 编辑预约订单
     *
     * @param order
     */
    @Override
    public Result edit(Order order) {
        try {
            System.out.println("+++++++++++++++++++++++++++++++++"+order.getOrderDate());
            System.out.println("-------------------------------"+DateUtils.parseDate2String(order.getOrderDate()));
            //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("orderDate",DateUtils.parseDate2String(order.getOrderDate()));
            OrderSetting orderSetting = orderSettingMapper.selectOne(wrapper);
            if (orderSetting == null) {
                //指定日期没有进行预约设置，无法完成体检预约
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if (reservations >= number) {
                //已经约满，无法预约
                return new Result(false, MessageConstant.ORDER_FULL);
            }
            //通过map来获取预约信息
            Map map = baseMapper.findById(order.getId());
//            String orderStatus = (String) map.get("orderStatus");

            //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
            Member member = memberMapper.selectById(order.getMemberId());
            if (member != null) {
                //判断是否在重复预约
                Integer memberId = member.getId();//会员ID
//                Date newOrderDate = DateUtils.parseString2Date(order.getOrderDate().toString());
                Date orderDate = order.getOrderDate();
                String date2String = DateUtils.parseDate2String(orderDate);
                Date newOrderDate = DateUtils.parseString2Date(date2String);//新预约日期
                Integer setmealId = order.getSetmealId();//套餐ID
                Integer addressId = order.getAddressId();//地址ID
                Order order1 = new Order(memberId, newOrderDate, setmealId, addressId);
                //根据条件进行查询
                List<Order> list = baseMapper.findByCondition(order1);
                if (list != null && list.size() > 1) {
                    //说明用户在重复预约，无法完成再次预约
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }
            //4.获取老的预约的时间
            Date oldOrderDate = (Date) map.get("orderDate");//老预约日期
            System.out.println("++++++++++++++++++111111111111111111111111"+oldOrderDate.toString());
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("orderDate",oldOrderDate);
            OrderSetting oldOrderSetting = orderSettingMapper.selectOne(wrapper1);

            //修改体检中心数据
//            MemberFileReport memberFileReport = new MemberFileReport();
//            memberFileReport.setName((String) map.get("member"));
//            memberFileReport.setSetmealId((Integer) map.get("setmealId"));
//            memberFileReport.setPhoneNumber((String)map.get("telephone"));
//            memberFileReport.setCheckuptime(oldOrderDate);
            QueryWrapper wrapper2=new QueryWrapper();
            wrapper2.eq("checkuptime",oldOrderDate);
           wrapper2.eq("name",(String) map.get("member"));
           wrapper2.eq("setmealId",(Integer) map.get("setmealId"));
           wrapper2.eq("phoneNumber",(String)map.get("telephone"));
            MemberFileReport idByInformation = memberFileReportMapper.selectOne(wrapper2);

            MemberFileReport memberFileReport01 = new MemberFileReport();
            memberFileReport01.setId(idByInformation.getId());
            memberFileReport01.setName((String) map.get("member"));
            memberFileReport01.setSetmealId(order.getSetmealId());
            Setmeal setmeal = setmealMapper.selectById(order.getSetmealId());
            memberFileReport01.setSetmealName(setmeal.getName());//套餐名称
            Date orderDate2 = order.getOrderDate();
            String date2String2 = DateUtils.parseDate2String(orderDate2);
            Date newOrderDate2 = DateUtils.parseString2Date(date2String2);//新预约日期
            memberFileReport01.setCheckuptime(newOrderDate2);
            memberFileReportMapper.updateById(memberFileReport01);

            //5、预约成功，更新当日的已预约人数
            baseMapper.updateById(order);
            /*//预约状态（是否到诊）是否相同
            if (!orderStatus.equals(order.getOrderStatus())) {
                //预约时间 是否相同 相同仅仅修改数据库状态
                if (oldOrderDate.equals(order.getOrderDate())) {
                    orderSettingDao.editReservationsByOrderDate(orderSetting);
                } else {
                    //更新已预约人数
                    orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
                    oldOrderSetting.setReservations(oldOrderSetting.getReservations() - 1);//设置老日期已预约人数-1
                    orderSettingDao.editReservationsByOrderDate(orderSetting);
                    orderSettingDao.editReservationsByOrderDate(oldOrderSetting);
                }
            }else {
                //预约时间 是否相同 相同仅仅修改数据库状态
                if (oldOrderDate.equals(order.getOrderDate())) {
                    orderSettingDao.editReservationsByOrderDate(orderSetting);
                } else {
                    //更新已预约人数
                    orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
                    oldOrderSetting.setReservations(oldOrderSetting.getReservations() - 1);//设置老日期已预约人数-1
                    orderSettingDao.editReservationsByOrderDate(orderSetting);
                    orderSettingDao.editReservationsByOrderDate(oldOrderSetting);
                }
            }*/

            //预约时间 是否相同 相同仅仅修改数据库状态
            if (oldOrderDate.equals(newOrderDate2)) {
                QueryWrapper wrapper3=new QueryWrapper();
                wrapper3.eq("orderDate",orderSetting.getOrderDate());
                orderSettingMapper.update(orderSetting,wrapper3);
            } else {
                //更新已预约人数
                orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
                oldOrderSetting.setReservations(oldOrderSetting.getReservations() - 1);//设置老日期已预约人数-1
                orderSettingMapper.updateById(orderSetting);
                orderSettingMapper.updateById(oldOrderSetting);
//                orderSettingDao.editReservationsByOrderDate(orderSetting);
//                orderSettingDao.editReservationsByOrderDate(oldOrderSetting);
            }
            return new Result(true, MessageConstant.EDIT_ORDERLIST_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_ORDERLIST_FAIL);
        }
    }

    /**
     * 删除预约订单
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //通过map来获取预约信息
        Map map = baseMapper.findById(id);
        Date orderDate = (Date) map.get("orderDate");
        //检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("orderDate",orderDate);
        OrderSetting orderSetting = orderSettingMapper.selectOne(wrapper);

        orderSetting.setReservations(orderSetting.getReservations() - 1);//设置已预约人数-1
        orderSettingMapper.updateById(orderSetting);

        baseMapper.deleteById(id);

        //删除体检中心数据
//        MemberFileReport memberFileReport = new MemberFileReport();
//        memberFileReport.setName((String) map.get("member"));
//        memberFileReport.setSetmealName((String) map.get("setmeal"));
//        memberFileReport.setPhoneNumber((String) map.get("telephone"));
//        memberFileReport.setSex((String) map.get("sex"));
//        memberFileReport.setCheckuptime(orderDate);
//        System.out.println(memberFileReport);
        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("name",(String) map.get("member"));
        wrapper1.eq("checkuptime",orderDate);
        wrapper1.eq("phoneNumber",(String) map.get("telephone"));
        wrapper1.eq("setmealName",(String) map.get("setmeal"));
        memberFileReportMapper.delete(wrapper1);
    }

}